import InterServer from "../config/server";
import {
    localStorageSyncServer,
    camelCase,
    bytesNumber
} from "../js/common"
var APP = getApp();

const formatTime = date => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};

const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : '0' + n
};

// 将时间变成两位
function toDouDate(date) {
    if (date.toString().length == 1) {
        return '0' + date.toString()
    } else {
        return date.toString()
    }
}

//函数节流（防止快速点击）
function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 2000
    }
    let _lastTime = null
        // 返回新的函数
    return function() {
        let _nowTime = +new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments) //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}

/**
 * 数字转大写
 * @param lifeNumber
 * @return
 */
// function transformNumToChinese(num){
//      // 提供中文数字
//   var cnum = ['一', '二', '三', '四', '五', '六', '七', '八', '九','十','百','千','万'];
//   let result = "";
//
//   return result;
// }

// 时长转换为时间格式 单位秒
function transformTimeToClock(seconds) {
    let [h, m, s] = [parseInt(seconds / 3600), parseInt(seconds / 60) % 60, seconds % 60];
    return formatNumber(h) + ":" + formatNumber(m) + ":" + formatNumber(s)
}

/**
 * 设置标题
 * @param title
 */
function setWxNavBarTitle(title) {
    wx.setNavigationBarTitle({
        title: title
    })
}
/**
 * 设置标题字体，背景颜色
 */
function setNavigationBarColor(font = "#000000", bg = '#333', dur = 0, effect = "linear") {
    wx.setNavigationBarColor({
        frontColor: font,
        backgroundColor: bg,
        animation: {
            duration: dur,
            timingFunc: effect
        }
    });
}

/**
 * 微信登录授权
 */
function loginOauth(isOauth) {
    var APP = getApp();
    console.log("登录")
    return new Promise((resolve, reject) => {
        if (localStorageSyncServer.get("Token")) {
            // 已登录
        } else {
            InterServer.loginAndRegister({
                "projectType": 5,
                "code": APP.globalData.code
            }).then(function(ret) {
                console.log(ret)
                if (ret.status < 5e2) {
                    APP.globalData.token = ret.data.token;
                    localStorageSyncServer.set("Token", ret.data.token); // token 存储
                    APP.globalData.openId = ret.data.openId;
                    APP.globalData.userInfo.birthday = ret.data.birthday;
                    APP.globalData.userInfo.userInfoId =
                        ret.data.userInfoId;
                    APP.globalData.userInfo.mobile = ret.data.mobile;
                    APP.globalData.userInfo.avatarUrl = ret.data.avatarUrl;
                    APP.globalData.successloginStatue = ret.status;
                    wx.hideLoading();
                    resolve(ret);
                    if (ret.status == 200) {
                        APP.globalData.registerTag = 1;
                        if (isOauth) {
                            wx.customReLaunch("/pages/index/index");
                        }
                    } else if (ret.status == 300) {
                        APP.globalData.registerTag = 0;
                        //wx.customReLaunch('/pages/personal_info/personal_info')
                    }
                } else {
                    console.log(ret);
                    wx.showToast({
                        icon: "none",
                        title: ret.data.info
                    });
                }
            });
        }
    })
}

/**
 * 获取用户信息
 */
function getUserInfo() {
    return new Promise((resolve, reject) => {
        InterServer.getUserInfo({
            third_party_type: 1
        }).then(userInfo => { // 获取用户信息
            let info = camelCase(userInfo.data);
            let nickname = info.nickname;
            APP.globalData.userInfo = info;
            if (APP.globalData.userInfo.sex == 0) {
                APP.globalData.userInfo.sex == 2
            }
            resolve(APP.globalData.userInfo, "done")
        });
    })
}
/**
 * 根据支付类型查询
 * 支付密码币数和剩余密码币
 * coinType  支付类型：101充值 1101月卡
 * monthCardConfigId 对应月卡类型
 * callBackFn  回调函数
 */
function queryCoinByType(coinType, monthCardConfigId, callBackFn) {
    InterServer.queryCoinByType({
        userInfoId: APP.globalData.userInfo.userInfoId,
        coinType,
        monthCardConfigId
    }).then(res => {
        if (res.status == 200) {
            let payData = res.data
            wx.showModal({
                content: payData.enoughTag ? '当前需支付' + payData.payCoinAmount + '密码果\r\n当前余额：' + payData.userCoinAmount + '密码果' : '当前需支付' + payData.payCoinAmount + '密码果\r\n当前余额：' + payData.userCoinAmount + '密码果\r\n密码果不足支付',
                cancelText: '取消',
                confirmText: payData.enoughTag ? '支付' : '充值',
                success: function(res) {
                    if (res.confirm) {
                        if (!payData.enoughTag) {
                            wx.navigateTo({
                                url: '/pages/wallet/wallet',
                            })
                        } else {
                            callBackFn()
                        }
                    }
                }
            })
        }
    })
}
/**
 * 用户行为统计
 * moduleType  分享类型：1、小程序，2、他人报告
 * shareUserInfoId 分享者ID
 * relationshipInfoId
 */
function addUserShareRecord(moduleType, shareUserInfoId, relationshipInfoId) {
    InterServer.addUserShareRecord({
        moduleType: moduleType,
        shareUserInfoId: shareUserInfoId,
        relationshipInfoId: relationshipInfoId
    }).then(res => {
        if (res.status == 200) {
            console.log(res)
        }
    })
}
/**
 * 点击分享记录
 * moduleType  分享类型：1、小程序，2、他人报告
 * shareUserInfoId 分享者ID
 * personId
 */
function userShareClickRecord(moduleType, shareUserInfoId, personId) {
    InterServer.userShareClickRecord({
        moduleType: moduleType,
        shareUserInfoId: shareUserInfoId,
        personId: personId,
        userInfoId: APP.globalData.userInfo.userInfoId,
        registerTag: APP.globalData.registerTag
    }).then(res => {
        if (res.status == 200) {
            console.log(res)
        }
    })
}
// 向后台发送formID
function sendFormId(formId) {

    if (!isNaN(formId) && formId != '') {
        InterServer.sendFormId({
            form_id: formId
        }).then((val) => {
            if (val.code == 200) {
                console.log(val.msg)
            }
        })
    }

}
/**
 * canvas绘图文本换行
 *
 * ctx 画布
 * str 绘制的字符串
 * initX 初始坐标X
 * initY 初始坐标Y
 * rowHeight 每一行的高度
 * rowWidth 每一行的宽度
 */
function canvasNewLine(ctx, str, initX, initY, rowWidth, rowHeight) {
    var lineWidth = 0;
    var lineWidthNext = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    var rowNum = 1; //绘制了多少行
    for (let i = 0; i < str.length; i++) {
        if (lineWidth + lineWidthNext > rowWidth) {
            ctx.fillText(str.substring(lastSubStrIndex, i), initX, initY); //绘制截取部分
            initY += rowHeight;
            lineWidth = 0;
            lastSubStrIndex = i;
            ++rowNum
        }
        if (i == str.length - 1) { //绘制最后一行
            ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
        }
        lineWidth += ctx.measureText(str[i]).width;
        lineWidthNext = str[i + 1] ? ctx.measureText(str[i + 1]).width : 0
    }
    return rowNum
}
//获取当前年月日
function getDate() {
    //获取当前时间
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    return year + "-" + month;
}
/**
 * canvas 字符串省略号
 * ctx 画布对象
 * str 字符串
 * width 截取的长度
 */
function cavansEllipsis(ctx, str, width) {
    let len = 0
    let strNew = ''
    let w = width - ctx.measureText('...').width
    for (let i = 0; i < str.length; i++) {
        len += ctx.measureText(str[i]).width
        if (len < w) {
            strNew += str[i]
        } else {
            strNew += '...'
            break
        }
    }
    return strNew
}

// 下载图片
function downCancasImgFun(that, url, obj, key) {
    return new Promise((resolve, reject) => {
        wx.downloadFile({
            url: url,
            success: function(res) {
                if (res.statusCode == 200) {
                    //获取下载的图片信息，判断是否可用
                    wx.getImageInfo({
                        src: res.tempFilePath,
                        success(res) {
                            that.data[obj][key] = res.path
                            that.setData({
                                [obj]: that.data[obj]
                            })
                            resolve(res.path)
                        },
                        fail(res) {
                            console.log('生成图片错误')
                            that.data[obj][key] = ''
                            that.setData({
                                [obj]: that.data[obj]
                            })
                        }
                    })
                }
            },
            fail: function(res) {
                console.log(res)
            }
        })
    })
}
//实现登录逻辑

//判断是否登录
function isLogin() {
    let Token = localStorageSyncServer.get("Token", 1.8)
    return new Promise((resolve, reject) => {
        if (!Token) {
            //实现登录逻辑
            // uni.showModal({
            //   title: '提示',
            //   content: '该功能需要登录，才可以查看',
            //   success: function (res) {
            //     if (res.confirm) {
            //       uni.navigateTo({
            //         url: "./login"
            //       })
            //     } else if (res.cancel) {
            //       console.log(res.cancel)
            //     }
            //   }
            // });
            uni.navigateTo({
                url: "./login"
            })
            resolve(false)
        } else {
            resolve(true)
        }
    })
}

export {
    transformTimeToClock,
    throttle,
    formatTime,
    setWxNavBarTitle,
    setNavigationBarColor,
    loginOauth,
    getUserInfo,
    sendFormId,
    canvasNewLine,
    cavansEllipsis,
    downCancasImgFun,
    queryCoinByType,
    addUserShareRecord,
    userShareClickRecord,
    toDouDate,
    getDate,
    isLogin
};